package com.manager.service;


import com.manager.base.BaseResponse;
import com.manager.entity.User;
import com.manager.mapper.UserMapper;
import com.manager.util.*;
import com.manager.vo.UserVo;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author zhou
 * @date 2021/07/10 19:25
 **/
@Service
public class UserService {

  @Resource
  private UserMapper userMapper;

  @Resource
  private SendMailUtils sendMailUtils;

  @Resource
  private RedisUtils redisUtils;


  /**
   * 邮件服务
   *
   * @param email 邮箱
   * @return com.manager.base.BaseResponse
   * @author zhou
   * @date 2021/07/12 21:51
   */
  public BaseResponse sendMail(String email) {
    // 随机生成6位验证码
    String code = sendMailUtils.randomCode();
    if (!StringUtils.isEmpty(email) && RegexUtils.checkEmail(email)) {
      StringBuilder title = new StringBuilder();
      title.append("doc manager 平台");
      StringBuilder content = new StringBuilder();
      // TODO
      content.append("</p>欢迎注册doc Manager,您注册验证码为:" + code + "</p>");
      sendMailUtils.sendNormalEmail(title.toString(), content.toString(), email);
      redisUtils.set(email, code, 1800);
      return BaseResponse.success("邮件发送成功");
    }
    return BaseResponse.error("邮件发送失败,请检查邮箱是否正确");
  }

  /**
   * 用户注册服务
   *
   * @param email      邮箱
   * @param password   密码
   * @param ipaddr     注册IP地址
   * @param verifyCode 邮箱验证码
   * @return com.manager.base.BaseResponse
   * @author zhou
   * @date 2021/07/12 21:49
   */
  public BaseResponse register(String email, String password, String ipaddr, String verifyCode) {
    if (StringUtils.isEmpty(password) || password.length() > 18 || password.length() < 6) {
      return BaseResponse.error("密码仅支持6-18位的密码");
    }
    if (!redisUtils.hasKey(email)) {
      return BaseResponse.error("邮件超时,请重新发送");
    }
    String code = (String) redisUtils.get(email);
    if (!code.equals(verifyCode)) {
      return BaseResponse.error("邮件验证码不正确");
    }
    password = BCrypt.hashpw(password, BCrypt.gensalt());
    userMapper.addUser(new User(email.replace("@", ""), email, password, ipaddr));
    return BaseResponse.success("注册成功");
  }


  /**
   * 用户登陆服务
   *
   * @param account  登陆账号
   * @param password 密码
   * @return com.manager.base.BaseResponse
   * @author zhou
   * @date 2021/07/12 21:48
   */
  public BaseResponse userLogin(String account, String password) {
    User user = null;
    UserVo userVo = null;
    if (RegexUtils.checkEmail(account)) {
      user = userMapper.selectUserByEmail(account);
    } else {
      user = userMapper.selectUserByUserName(account);
    }
    if (BCrypt.checkpw(password, user.getPassword())) {
      userVo = userMapper.selectUserById(user.getId());
      userVo.setToken(TonkenUtils.getToken(userVo.getId()));
      return BaseResponse.success("登陆成功", userVo);
    }
    return BaseResponse.error("登陆失败,请检查您输入的用户名和密码");
  }

}
